package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.controller.dto.LoginDTO;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.controller.request.UserPageRequest;
import com.example.springboot.entity.User;
import com.example.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin  //解决跨域错误
@RestController
@RequestMapping("/user")
//是rest风格的usercontroller
public class UserController{

    @Autowired
    IUserService userService;


    @PostMapping("/login")
//   登录
    public Result login(@RequestBody LoginRequest request){
        LoginDTO login = userService.login(request);
        if(login == null){
            return Result.error("用户名或密码错误");
        }
        return Result.success(login);
    }

    //    UserPageRequest传入用户名和电话信息
    @GetMapping("/page")
    public Result page(UserPageRequest userPageRequest){
        //        返回数据 Result.success传入一个对象
        return Result.success(userService.page(userPageRequest));

    }

//    post put get delete对应增改查删四类操作
    //    新增会员
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        userService.save(user);
        return Result.success();
    }
//用户余额充值
    @PostMapping("/account")//    积分
    public Result account(@RequestBody User user){
        userService.handleAccount(user);
        return Result.success();
    }

    //用户注册
    @PostMapping("/register")//    积分
    public Result register(@RequestBody User user){
        userService.register(user);
        return Result.success();
    }

//    更新会员信息
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        userService.update(user);
        return Result.success();
    }

    //    获取用户列表
    @GetMapping("/list")
    public Result list(){
        //        返回数据
        List<User> users=userService.list();
//        System.out.println("users内容是"+users);
        return Result.success(users);

    }


//    根据ID更新用户信息
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        User user =userService.getById(id);
        return Result.success(user);

    }

    //删除操作:
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        userService.deleteById(id);
        return Result.success();
    }



    /*
    最初是通过List返回所有数据,而建立Result后采用Result返回数据
    @GetMapping("/list")
    public List<User> listUsers(){
        return userService.listUsers();
    }
     */
}
